package com.android.fragmentdemo.defineviews

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.android.fragmentdemo.R

class StrokeThroughTextView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : AppCompatTextView(context, attributeSet) {

    private var strokeWidth = 0F

    private var strokeColor = 0

    private val rect by lazy {
        Rect()
    }

    private val mPaint by lazy {
        Paint().apply {
            isDither = true
            isAntiAlias = true
        }
    }

    init {
       context.obtainStyledAttributes(attributeSet, R.styleable.StrokeThroughTextView).apply {
           strokeColor = getColor(
               R.styleable.StrokeThroughTextView_stroke_color,
               resources.getColor(R.color.color_DC8717)
           )
           strokeWidth = getDimension(
               R.styleable.StrokeThroughTextView_stroke_width,
               resources.getDimension(R.dimen.dp_2)
           )
           recycle()
       }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.apply {
            mPaint.color = strokeColor
            mPaint.strokeWidth = strokeWidth
            val content = text.toString()
            if (content.isNotEmpty()) {
                //mPaint.getTextBounds(text.toString(),0,text.toString().length,rect)
                //val y = baseline + lineSpacingExtra / 2 //下划线y坐标
                drawLine(0F, measuredHeight.toFloat() / 2, measuredWidth.toFloat(), measuredHeight.toFloat() / 2, mPaint)
            }
        }
    }
}